package com.atguigu.controller;

import com.atguigu.config.RandomUtil;
import com.atguigu.result.Result;
import com.atguigu.service.MsmService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@Slf4j
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable("phone") String phone){
        log.info("手机号：{}", phone);
        //从redis中获取验证码，如果获取到，返回ok
        //key：手机号   value：验证码
        String code = (String)redisTemplate.opsForValue().get(phone);

        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }

        //如果获取不到，生成验证码
        code = RandomStringUtils.randomNumeric(4);
        boolean isSend = msmService.send(phone, code);//发送验证码

        //通过使用手机号发送，生成验证码后放到redis中，并设置有效时间（两分钟内有效）
        if(isSend){
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }
    }
}
